<template>
  <div class="my-upgrade">
    <cell-group>
      <field v-model="nowLevel" label-width="100px" label="现在等级：" placeholder="米粉" readonly />
      <field
        @click="popupType = 'grade', showPopup = true"
        v-model="selectedAgencyLevel.level_name"
        label-width="100px"
        label="升级等级："
        readonly
        right-icon="arrow-down"
      />
      <field
        @click="popupType = 'payType', showPopup = true"
        v-model="selectedPayType.name"
        label-width="100px"
        label="打款方式："
        readonly
        right-icon="arrow-down"
      />
      <field
        v-if="selectedPayType.id == 2"
        v-model="bankName"
        label-width="100px"
        label="银行名称："
        placeholder="请输入银行名称"
      />
      <field
        v-if="selectedPayType.id == 2"
        v-model="accountName"
        label-width="100px"
        label="开户实名："
        placeholder="请输入开户实名"
      />
      <field
        v-if="selectedPayType.id == 2"
        v-model="account"
        label-width="100px"
        label="银行卡账号："
        placeholder="请输入你的银行卡账号"
      />
      <field
        v-if="selectedPayType.id == 1"
        v-model="account"
        label-width="100px"
        label="支付宝账号："
        placeholder="请输入你的支付宝账号"
      />

      <field
        v-model="selectedAgencyLevel.money"
        label-width="100px"
        label="金额："
        placeholder="请输入打款金额"
        type="number"
        readonly
      />
      <field
        @click="popupType = 'date', showPopup = true"
        v-model="time"
        label-width="100px"
        label="打款日期："
        readonly
        placeholder="请选择打款日期"
        right-icon="arrow-down"
      />
      <field v-model="remark" label-width="100px" label="备注：" placeholder="如有说明可填写备注" />

      <div class="upload-proof">
        <div class="upload-proof-text">
          打款凭证
          <br />(1-3张)：
        </div>
        <uploader
          :max-count="3"
          v-model="payImgList"
          :after-read="afterRead"
          :max-size="imgMaxSize"
          @oversize="oversize"
        />
      </div>
      <div class="upload-proof">
        <div class="upload-proof-text">
          手持证
          <br />(1张)：
        </div>
        <uploader
          :max-count="1"
          v-model="handImgList"
          :after-read="afterRead"
          :max-size="imgMaxSize"
          @oversize="oversize"
        />
      </div>
    </cell-group>

    <pay-info :type="selectedPayType.id"></pay-info>

    <div class="submit">
      <van-button
        type="info"
        size="large"
        @click="upgrade"
        :disabled="isSubmitting"  :loading="isSubmitting" :loading-text="'正在提交'"
      >{{isSubmitting ? '正在提交' : '确认升级'}}</van-button>
    </div>

    <popup :show="showPopup" @onCancel="onCancel">
      <div v-if="popupType == 'grade'">
        <picker
          @cancel="onCancel"
          value-key="level_name"
          show-toolbar
          :columns="agencyLevelList"
          @confirm="onConfirm"
        />
      </div>
      <div v-if="popupType == 'payType'">
        <picker
          @cancel="onCancel"
          value-key="name"
          show-toolbar
          :columns="payTypeList"
          @confirm="onConfirm"
        />
      </div>
      <div v-if="popupType == 'date'">
        <datetime-picker
          v-model="currentDate"
          type="date"
          :max-date="maxDate"
          :formatter="formatter"
          @confirm="onConfirm"
          @cancel="onCancel"
        />
      </div>
    </popup>
  </div>
</template>

<script>
import {
  Field,
  Cell,
  CellGroup,
  Uploader,
  Button,
  Picker,
  Toast,
  DatetimePicker
} from "vant";
import payInfo from "../components/pay_info.vue";
import popup from "../components/popup.vue";
var moment = require("moment");
import http from "../service/myHttp.js";
import urls from "../service/url.js";
import { mapState } from "vuex";
import {
  getImageMetaInfo,
  getImageAfterCompressFromCanvas,
  getImageAfterCompressFromImgzip,
  getImageAfterCompressBatch
} from "../service/imageCompress.js";
import imgMaxSize from "../mixins/img_maxsize.js";

export default {
  components: {
    Field,
    Cell,
    CellGroup,
    Uploader,
    vanButton: Button,
    payInfo,
    popup,
    Picker,
    DatetimePicker
  },
  mixins: [imgMaxSize],
  data() {
    return {
      showPopup: false,
      popupType: "grade",
      agencyLevelList: [
        {
          id: 0,
          level_name: "全部"
        }
      ],
      selectedAgencyLevel: {
        id: 0,
        level_name: "全部"
      },
      selectedPayType: {
        id: 1,
        name: "支付宝"
      },
      payTypeList: [
        {
          id: 1,
          name: "支付宝"
        },
        {
          id: 2,
          name: "银行转账"
        }
      ],
      value: "",
      nowLevel: "",
      maxDate: new Date(),
      currentDate: new Date(),
      // upgradeLevel: '',
      payImgList: [],
      handImgList: [],
      bankName: "",
      accountName: "",
      account: "",
      payMoney: "",
      remark: "",
      time: "",
      agencyLevelList: [
        // {
        //   id: 0,
        //   level_name: "全部"
        // }
      ],
      agentInfo: {},
      isSubmitting: false
    };
  },
  computed: {
    ...mapState({
      userInfo: state => state.login_module.userinfo,
      countAlias: "userInfo"
    })
  },
  async mounted() {
    // 获取上级代理信息
    await this.getAgentInfo();

    // 获取代理等级列表
    await this.getAgencyLevel();

    // 获取用户当前等级信息
    let agencyLevelList = [];
    let agentId = null;
    this.agencyLevelList.forEach(item => {
      if (item.level_name == this.agentInfo.level_name) {
        agentId = item.id;
        this.nowLevel = item.level_name;
      }
    });

    // 获取用户可升级等级列表
    this.agencyLevelList.forEach(item => {
      if (Number(agentId) > Number(item.id)) {
        agencyLevelList.push(item);
      }
    });

    this.agencyLevelList = agencyLevelList;

    // 初始化默认升级等级
    this.selectedAgencyLevel = this.agencyLevelList[0];
  },
  methods: {
    formatter(type, value) {
      if (type === "year") {
        return `${value}年`;
      } else if (type === "month") {
        return `${value}月`;
      } else if (type === "day") {
        return `${value}日`;
      }
      return value;
    },

    // 升级操作
    async upgrade() {
      let applyInfo = {
        account: this.account,
        payMoney: this.selectedAgencyLevel.money,
        remark: this.remark,
        payImage: this.payImgList.length
          ? [...this.payImgList].map(item => item.content)
          : "",
        handDocuments: this.handImgList.length
          ? this.handImgList[0].content
          : "",
        agentLevel: this.selectedAgencyLevel.id,
        payType: this.selectedPayType.id,
        payTime: moment(this.currentDate).format("YYYY-MM-DD"),
        applyType: 2,
        applyBeforeLevel: this.agentInfo.level_id
      };

      let verify = {
        account: "账户",
        payMoney: "金额",
        payImage: "打款凭证",
        handDocuments: "手持证"
      };

      // 当支付方式为 支付宝 时
      if (this.selectedPayType.id == 2) {
        applyInfo = Object.assign({}, applyInfo, {
          bankName: this.bankName,
          accountName: this.accountName
        });

        verify = Object.assign({}, verify, {
          bankName: "银行名称",
          accountName: "开户名称"
        });
      }

      for (let item in applyInfo) {
        if (!applyInfo[item]) {
          if (item in verify) {
            // console.log(item);
            Toast(verify[item] + "不能为空");
            return false;
          }
        }
      }

      // 压缩图片
      let payImages = await getImageAfterCompressBatch(applyInfo.payImage);
      // console.log(payImages);
      // let headImgs = await getImageAfterCompressBatch([applyInfo.headImg]);
      let handDocuments = await getImageAfterCompressBatch([
        applyInfo.handDocuments
      ]);
      applyInfo.payImage = payImages;
      // applyInfo.headImg = headImgs[0];
      applyInfo.handDocuments = handDocuments[0];

      // Toast("正在提交，请稍候");
      this.isSubmitting = true;
      http.post(urls.TJDLSQ, applyInfo).then(res => {
        this.isSubmitting = false;
        if (res.data.code == 200) {
          let data = res.data.data;
          // this.agentInfo = data;
          Toast.success("升级申请成功");

          setTimeout(() => {
            this.$router.go(-1);
          }, 1000);

          resolve();
        }
      });
    },

    // 获取上级代理信息
    getAgentInfo() {
      return new Promise((resolve, reject) => {
        http
          .post(urls.DLXQ, {
            id: this.userInfo.id
          })
          .then(res => {
            if (res.data.code == 200) {
              let data = res.data.data;
              this.agentInfo = data;
              resolve();
            }
          });
      });
    },

    // 获取代理等级列表
    getAgencyLevel() {
      return new Promise((resolve, reject) => {
        http
          .post(urls.JZDLXLK, {
            id: this.userInfo.id,
            tokenid: this.userInfo.id
          })
          .then(res => {
            if (res.data.code == 200) {
              this.agencyLevelList = res.data.data;
              resolve();
              // this.agencyLevelList.push({ id: 0, level_name: "全部" });
            }
          });
      });
    },
    afterRead(file) {
      // console.log(file);
      // this.filesList.push({url: file.content})
    },
    onCancel() {
      this.showPopup = false;
    },
    onConfirm(value) {
      if (this.popupType == "payType") {
        this.selectedPayType = value;
      } else if (this.popupType == "grade") {
        this.selectedAgencyLevel = value;
      } else if (this.popupType == "date") {
        this.time = moment(value).format("YYYY年MM月DD日");
      }
      this.showPopup = false;
      // this.pageNumber = 1
      // this.allList = []

      // this.loading = false
      // this.finished = false
    }
  }
};
</script>

<style scoped>
.upload-proof {
  padding: 10px 15px;
  display: flex;
}

.upload-proof-text {
  width: 100px;
  /* padding-right: 10px; */
  color: #323233;
  text-align: left;
}

.submit {
  margin-bottom: 30px;
}
</style>

<style>
.my-upgrade .van-uploader__upload,
.my-upgrade .van-uploader__preview {
  /* transform: scale(0.8); */
}
</style>

